package repo

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

func Download(url string, relativePath string, downloadDir string, token string) (string, error) {
	// 获取文件名
	fileName := filepath.Base(relativePath)
	dir := filepath.Dir(relativePath)
	destDir := filepath.Join(downloadDir, dir)
	err := os.MkdirAll(destDir, os.ModePerm)
	if err != nil {
		return "", fmt.Errorf("failed to mk dir: %v", err)
	}
	destPath := filepath.Join(destDir, fileName)
	// 创建目标文件
	out, err := os.Create(destPath)
	if err != nil {
		return "", fmt.Errorf("failed to create file: %v", err)
	}
	defer out.Close()

	// 发送 HTTP GET 请求
	request, err := http.NewRequest("GET", url+"?relativePath="+relativePath, nil)
	request.Header.Set("Authorization", "Bearer "+token)
	resp, err := client.Do(request)
	if err != nil {
		return "", fmt.Errorf("failed to download file: %v", err)
	}
	defer resp.Body.Close()

	// 检查 HTTP 响应状态码
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("bad status: %s", resp.Status)
	}

	// 将响应体写入文件
	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return "", fmt.Errorf("failed to save file: %v", err)
	}

	return destPath, nil
}
